package com.example.xt.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.xt.common.Constants;
import com.example.xt.common.Result;
import com.example.xt.entity.Medicine;
import com.example.xt.entity.Rder;
import com.example.xt.mapper.MedicineMapper;
import com.example.xt.mapper.OrdersMapper;
import com.example.xt.service.IMedicineService;
import com.example.xt.service.IRderService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2022-03-05
 */
@RestController
@RequestMapping("/orders")
public class OrdersController {
    @Resource
    private IRderService rderService;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private IMedicineService medicineService;
    @Resource
    private MedicineMapper medicineMapper;

    @PostMapping("/sum")
    public Result save() throws InterruptedException {
        ordersMapper.save0();
        ordersMapper.save1();
        ordersMapper.updata0();
        ordersMapper.updata1();
        ordersMapper.updata2();
        ordersMapper.updata3();
        return Result.success();
    }

    @PostMapping("/insert")
    public Result save(@RequestBody java.util.Collection<Rder> rder) {
        try {
            for (Rder i : rder) {
                ordersMapper.del(i.getId(), i.getNum());
            }
            return Result.success(rderService.saveBatch(rder));//修改为inters*****rder.time=NOW()
        } catch (Exception e) {
            return Result.error(Constants.CODE_403, "库存不足");
        }

    }

    @GetMapping("/page")//查询未过期的
    public Page findPage(@RequestParam Integer pageNum,
                         @RequestParam Integer pageSize,
                         @RequestParam(defaultValue = "") String pagename) {
        medicineMapper.exp();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("id");//根据ID倒序
        if (!"".equals(pagename)) {
            queryWrapper.like("name", pagename);//根据名称查
        }
        queryWrapper.inSql("id", "select id from medicine where ep*30-exp > 0 and stock>0");
        return medicineService.page(new Page<>(pageNum, pageSize), queryWrapper);
    }

    @GetMapping("/page/expire")//查询已经过期的
    public Page<Medicine> findPage(@RequestParam Integer pageNum,
                                   @RequestParam Integer pageSize
    ) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("id");//根据ID倒序

        queryWrapper.inSql("id", "select id from medicine where (ep*30-exp) < 1 and stock>0");

        return medicineService.page(new Page<>(pageNum, pageSize), queryWrapper);
    }


}
